import React, { useState, useEffect, useMemo } from 'react';
import { IssueType } from '@/types/aiCorrector';
import type { AICorrectionIssue, SortOption, PaginationConfig } from '@/types/aiCorrector';
import { useAiCorrectorStore } from '@/stores/useAiCorrectorStore';
import { compareByTitle } from '@/utils/utils';
import IssueCard from './IssueCard';
import PaginationControls from './PaginationControls';
import './animations.css'; // 我们将创建这个CSS文件


const IssueList: React.FC = () => {
  // 使用上下文获取所需的状态和方法
  const { 
    state, 
    updateFilters,
    startEdit, 
    isItemModified, 
    resetModifications, 
    applyAllModifications 
  } = useAiCorrectorStore();
  
  // 从上下文中获取所需的状态
  const { issues, editingIssueId, modifiedItems, filters } = state;
  
  // 本地状态
  const [activeTab, setActiveTab] = useState<IssueType | 'all'>('all');
  const [sortBy, setSortBy] = useState<SortOption>('itemId'); // 默认按检查项排序
  const [pagination, setPagination] = useState<PaginationConfig>({
    currentPage: 1,
    pageSize: 10,
    totalItems: 0
  });
  
  // 用于跟踪哪些问题项正在消失
  const [fadingIssueIds, setFadingIssueIds] = useState<string[]>([]);
  
  // 缓存的问题类型计数
  const [issueTypeCounts, setIssueTypeCounts] = useState<Record<string, number>>({});
  
  // 排序问题列表
  const sortIssues = (issues: AICorrectionIssue[], sortOption: SortOption) => {
    return [...issues].sort((a, b) => {
      switch (sortOption) {
        case 'severity':
          // 按严重程度排序（从高到低）
          return b.severity.localeCompare(a.severity);
        case 'type':
          // 按问题类型排序
          return a.type.localeCompare(b.type);
        case 'itemId':
          // 按检查项ID排序
            return compareByTitle({title: a.title, description: a.originalDescription || ''}, {title: b.title, description: b.originalDescription || ''});
        default:
          return 0;
      }
    });
  };
  
  // 根据筛选条件过滤问题
  const filteredIssues = useMemo(() => {
    // 应用筛选逻辑
    let filtered = [...issues];
    
    // 按问题类型筛选
    if (filters.issueType !== 'all') {
      filtered = filtered.filter(issue => issue.type === filters.issueType);
    }
    
    // 按严重程度筛选
    if (filters.severity !== 'all') {
      filtered = filtered.filter(issue => issue.severity === filters.severity);
    }
    
    // 应用排序
    return sortIssues(filtered, sortBy);
  }, [issues, filters, sortBy]);
  
  // 切换标签页
  const handleTabChange = (tab: IssueType | 'all') => {
    setActiveTab(tab);
    updateFilters({ issueType: tab });
    setPagination(prev => ({ ...prev, currentPage: 1 }));
  };
  
  // 切换排序方式
  const handleSortChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setSortBy(e.target.value as SortOption);
  };
  
  // 更新分页配置
  const updatePagination = (newPagination: Partial<PaginationConfig>) => {
    setPagination(prev => ({
      ...prev,
      ...newPagination
    }));
  };
  
  // 处理编辑问题
  const handleEditIssue = (issueId: string) => {
    startEdit(issueId);
  };
  
  // 只在初始化时和应用修改后更新问题类型计数
  useEffect(() => {
    updateIssueTypeCounts();
  }, [issues]); // 只依赖于原始issues数组，不依赖于filteredIssues
  
  // 更新问题类型计数 - 使用原始issues数组而不是filteredIssues
  const updateIssueTypeCounts = () => {
    const counts: Record<string, number> = {
      'all': issues.length
    };
    
    // 计算每种问题类型的数量
    Object.values(IssueType).forEach(type => {
      counts[type] = issues.filter(issue => issue.type === type).length;
    });
    
    setIssueTypeCounts(counts);
  };
  
  // 应用所有修改
  const handleApplyAll = () => {
    // 获取已修改的问题项ID
    const modifiedIssueIds = currentPageIssues
      .filter((issue: AICorrectionIssue) => isItemModified(issue.itemId))
      .map((issue: AICorrectionIssue) => issue.id);
    
    // 设置正在消失的问题项
    setFadingIssueIds(modifiedIssueIds);
    
    // 等待动画完成后再应用修改
    setTimeout(() => {
      applyAllModifications();
      setFadingIssueIds([]);
      // 更新分页信息
      updatePagination({
        totalItems: filteredIssues.length,
        currentPage: 1
      });
      // 应用修改后更新问题类型计数
      // 注意：这里不需要手动调用 updateIssueTypeCounts，因为 issues 会变化，触发 useEffect
    }, 500); // 与 CSS 动画时间一致
  };
  
  // 重置所有修改
  const handleResetAll = () => {
    resetModifications();
  };
  
  // 检查是否有修改过的项目
  const hasModifications = Object.keys(modifiedItems).length > 0;
  
  // 更新总项目数
  useEffect(() => {
    updatePagination({ totalItems: filteredIssues.length });
  }, [filteredIssues.length]);
  
  // 计算当前页的问题
  const { currentPage, pageSize } = pagination;
  const startIndex = (currentPage - 1) * pageSize;
  const endIndex = Math.min(startIndex + pageSize, filteredIssues.length);
  const currentPageIssues = filteredIssues.slice(startIndex, endIndex);
  
  // 获取问题类型标签
  const getIssueTypeLabel = (type: IssueType) => {
    switch (type) {
      case IssueType.TYPO:
        return '错别字';
      case IssueType.SEMANTIC:
        return '语义混乱';
      case IssueType.RISK_LEVEL:
        return '风险等级';
      case IssueType.COMPLIANCE_STATUS:
        return '合规状态';
      default:
        return type;
    }
  };
  
  // 获取问题类型数量
  const getIssueTypeCount = (type: IssueType | 'all') => {
    return issueTypeCounts[type] || 0;
  };
  
  return (
    <div className="bg-card rounded-lg shadow-sm p-6">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-xl font-semibold text-foreground">问题列表</h2>
        
        {/* 排序选择器 */}
        <div className="flex items-center">
          <label htmlFor="sort-select" className="text-sm text-muted-foreground mr-2">排序方式:</label>
          <select
            id="sort-select"
            className="text-sm border border-input rounded-lg p-2 focus:outline-none focus:ring-2 focus:ring-ring bg-background text-foreground"
            value={sortBy}
            onChange={handleSortChange}
          >
            <option value="itemId">按检查项</option>
            <option value="severity">按严重程度</option>
            <option value="type">按问题类型</option>
          </select>
        </div>
      </div>
      
      {/* 标签页 */}
      <div className="border-b border-border mb-6">
        <nav className="flex -mb-px">
          <button
            className={`py-3 px-4 text-sm font-medium border-b-2 ${
              activeTab === 'all'
                ? 'border-primary text-foreground'
                : 'border-transparent text-muted-foreground hover:text-foreground hover:border-border'
            }`}
            onClick={() => handleTabChange('all')}
          >
            全部 ({getIssueTypeCount('all')})
          </button>
          
          {Object.values(IssueType).map(type => (
            <button
              key={type}
              className={`py-3 px-4 text-sm font-medium border-b-2 ${
                activeTab === type
                  ? 'border-primary text-foreground'
                  : 'border-transparent text-muted-foreground hover:text-foreground hover:border-border'
              }`}
              onClick={() => handleTabChange(type)}
            >
              {getIssueTypeLabel(type)} ({getIssueTypeCount(type)})
            </button>
          ))}
        </nav>
      </div>
      
      {/* 修改状态栏 */}
      {hasModifications && (
        <div className="bg-success/10 border border-success/20 rounded-lg p-4 mb-6 flex justify-between items-center">
          <div className="text-success flex items-center gap-2">
            <span className="font-medium">检测到修改：</span>
            <span className="tag-status-active">
              已修改 {Object.keys(modifiedItems).length} 个检查项
            </span>
          </div>
          <div className="flex gap-2">
            <button
              onClick={handleResetAll}
              className="px-4 py-2 text-sm border border-input rounded-md hover:bg-secondary/50 text-secondary-foreground focus:outline-none focus:ring-2 focus:ring-ring"
            >
              取消所有修改
            </button>
            <button
              onClick={handleApplyAll}
              className="px-4 py-2 text-sm bg-green-500 text-white rounded-md hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500/50"
            >
              应用所有修改
            </button>
          </div>
        </div>
      )}
      
      {/* 问题列表 */}
      <div className="mb-6">
        {currentPageIssues.length > 0 ? (
          currentPageIssues.map(issue => {
            const isModified = isItemModified(issue.id);
            const isFading = fadingIssueIds.includes(issue.id);
            
            return (
              <div 
                key={issue.id}
                className={`issue-card-container ${isFading ? 'issue-fade-out' : ''}`}
              >
                <IssueCard 
                  issue={issue} 
                  onEdit={handleEditIssue}
                  isEditing={editingIssueId === issue.id}
                  isModified={isModified}
                />
              </div>
            );
          })
        ) : (
          <div className="text-center py-8">
            <span className="tag-check-type">
              {currentPageIssues.length === 0 && filteredIssues.length > 0 
                ? '没有符合当前筛选条件的问题' 
                : '没有发现任何问题'}
            </span>
          </div>
        )}
      </div>
      
      {/* 分页控件 */}
      {filteredIssues.length > 0 && (
        <PaginationControls
          totalItems={filteredIssues.length}
          onPageChange={(page, pageSize) => updatePagination({ currentPage: page, pageSize })}
          initialPage={pagination.currentPage}
          initialPageSize={pagination.pageSize}
        />
      )}
    </div>
  );
};

export default IssueList;
